<template>
  <div class="buy-now-box">
    <!--地址 收件人 电话-->
    <template v-if="role==4||5||6">
      <!--角色 代理 role=0-->
      <div class="pd10">

        <!--<div class="row-p row-sliers">-->
        <!--<span>收件人：{{addressData.name}}</span>-->
        <!--<span>{{addressData.phone}}</span>-->
        <!--</div>-->
        <div class="session">
          <span class="row-left">收件人:</span>
          <input type="text" v-model="recipients" placeholder="请输入">
        </div>
        <div class="session">
          <span class="row-left">电话:</span>
          <input type="tel" v-model="mobile" placeholder="请输入">
        </div>
        <div class="session">
          <span class="row-left">地址:</span>
          <textarea type="text" v-model="addressData.addressDetails" placeholder="请输入" @input="addrChange()"></textarea>
          <img @click="goAddress()" src="../../assets/images/location1-icon.png" alt="">
        </div>
        <!--<div class="row-p row-addr">-->
        <!--<span>地址：{{addressData.addressDetails}}{{addressData.name}}</span>-->

        <!--&lt;!&ndash;<img src="../../assets/images/location1-icon.png" alt="">&ndash;&gt;-->
        <!--<i class="arrow-right"></i>-->
        <!--</div>-->
      </div>
    </template>

    <div v-for="(item,index) in goodsInfo">
      <div class="pd10 row">
        <div class="col-left" ref="imgWidth" :style="{height:imgHeight}">
          <img :src="sourceUrl + item.goodsImg" alt="">
        </div>
        <div class="col-right">
          <div class="title clamp2">{{item.goodsName}}</div>
          <div class="price">￥{{item.shopPrice}}<span style="color: black"
                                                      v-if="!isActivity">/瓶(共{{item.goodsUnit}}瓶)</span></div>
          <div class="num-box">
            <div class="nb-left">
              <span>购买数量(单位:件)</span>
            </div>
            <div class="nb-right" v-if="!isActivity">
              <img src="../../assets/images/minus_icon.png" alt="" @click="minusNum(index)">
              <input class="buynum" type="number" v-model="item.goodsNum"/>
              <img src="../../assets/images/add_icon.png" alt="" @click="addNum(index)"/>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--服务商-->
    <div class="pd10 row2" @click="openPop();">
      <div class="r-left">
        <span>服务商</span>
      </div>

      <div class="r-right" style="font-size: 1rem">
        <img :src="sourceUrl+realImg" alt="" v-if="myLevel!=6&&isReplenishment">
        {{realName}}
        <i class="arrow-right"></i></div>
    </div>
    <!--服务商弹窗-->

    <div class="pop-box" v-if="showPop">
      <div style="height:100%;" @click="closePop();"></div>
      <div class="pop-bg">
        <ul class="tab-box">
          <li :key="index" v-for="(item,index) in tabs" @click="switchTab(index)"><span :class="{on:isOn==index}">{{item}}</span>
          </li>
        </ul>
        <ul class="tab-content">
          <li v-for="(item,index) in tabContent" :key="index"
              @click="selectRole(item.uid,item.name,item.level,item.imageUrl)">
            <div class="li-left">
              <div class="img-box">
                <img :src="sourceUrl+item.imageUrl" alt="">
              </div>
              <div class="name-box">
                <p class="p-name">{{item.name}}</p>

                <p class="p-agent" v-if="item.level==6" :class="{yellow:item.level==6}">区域总代</p>
                <p class="p-agent" v-if="item.level==4" :class="{blue:item.level==4}">银牌代理</p>
                <p class="p-agent" v-if="item.level==5" :class="{yellow:item.level==5}">金牌代理</p>
                <p class="p-agent" v-if="item.level==3" :class="{red:item.level==3}">侍酒师</p>
              </div>
            </div>
            <div class="li-right">
              <p class="p-gender">{{item.gender}} <span>{{item.age}}</span></p>

              <p class="p-distance" v-if="item.zfb==1">推荐人<span></span></p>
            </div>
          </li>

          <li v-show="tabContent!=null?tabContent.length<1:true">
            暂无数据
          </li>
        </ul>
      </div>
    </div>

    <template v-if="roleLevel==3&&!isUpgradePatch">
      <!--服务商 侍酒师 roleLevel=3-->
      <div class="pd10">
        <!--<p class="row-p">-->
        <!--<span>地址：</span>-->
        <!--<input type="text" id="address" placeholder="请输入"/>-->
        <!--<img src="../../assets/images/location1-icon.png" alt="">-->
        <!--</p>-->
        <ul class="input-box">

          <li>
            <span>包厢：</span><input type="text" placeholder="请输入" v-model="boxNum">
          </li>
          <li>
            <span>人数：</span>
            <div class="select-box">
              <select id="person" v-model="boxSum">
                <option :value="item" v-for="(item,index) in personNum">{{item}}</option>
              </select>
              <i class="arrow-down"></i>
            </div>
          </li>
          <li>
            <span>日期：</span><input type="date" v-model="boxDate"/>
          </li>
          <li>
            <span>时间：</span><input type="time" v-model="boxTime"/>
          </li>

          <li>
            <span>感谢金：</span>
            <input type="number" @keyup="value=value.replace(/[^\d{1,}\.\d{1,}|\d{1,1}]/g, '')" v-model="tip"  @input="inputAwarad" placeholder="请输入"/>
          </li>
          <li></li>
        </ul>
      </div>
    </template>

    <!--留言-->
    <div class="pd10">
      <div class="area-box">
        <label for="text-area">留言：</label>
        <textarea id="text-area" maxlength="150" v-model.trim="userMessage"></textarea>
      </div>
      <div class="mark-box">
        <p>快捷标签</p>
        <ul class="mark-list">
          <li :key="index" v-for="(item,index) in markList" @click="selectMark(index)">
            <span>{{item}}</span>
          </li>
        </ul>
      </div>
    </div>
    <!--文本提示弹窗-->
    <TextPop v-if="isPop" :textPop="popText"></TextPop>
    <!--底部-->
    <div class="submit-box">
      <div class="col-left">
        合计:
        <span v-if="tip==''">￥{{totalMoney ? totalMoney : 0 }}</span>
        <span
          v-if="tip!=''">￥{{parseFloat(totalMoney) + parseFloat(tip) ? (parseFloat(totalMoney) + parseFloat(tip)).toFixed(2) : 0
          }}</span>
        <span style="font-size: 13px;color: gray" v-if="!isActivity">原价:</span>

        <span class="original-price" v-if="!isActivity&&tip==''">￥{{originalPrice ? originalPrice : 0}}</span>

        <span class="original-price"
              v-if="!isActivity&&tip!=''">￥{{parseFloat(originalPrice) + parseFloat(tip) ? (parseFloat(originalPrice) + parseFloat(tip)).toFixed(2) : 0}}</span>

        <!--<span class="discount">￥{{totalMoney}}</span>-->
      </div>
      <div class="col-right" @click="purchaseApply()" v-if="myLevel==6&&isReplenishment">
        <span>确认下单</span>
      </div>
      <div class="col-right" @click="buyNowBtn()" v-else="myLevel==6&&isReplenishment">
        <span>确认付款</span>
      </div>
    </div>
    <!--提交弹窗-->
    <div class="pay-pop" v-if="payPopShow">
      <div style="width:100%;height:100%;" @click="payPopShow=false"></div>
      <div class="pay-bg">
        <p class="price" v-if="tip==''">￥{{totalMoney ? totalMoney : 0}}</p>
        <p class="price" v-if="tip!=''">
          ￥{{parseFloat(totalMoney) + parseFloat(tip) ? (parseFloat(totalMoney) + parseFloat(tip)).toFixed(2) : 0 }}</p>
        <label><input name="pay" type="radio" value="0" v-model="payMode"/><span>微信支付</span></label>
        <label><input name="pay" type="radio" value="1" v-model="payMode"/><span>余额支付</span></label>
        <div class="pay-btn" @click="payBtn()">支付</div>
      </div>
    </div>
    <div class="pay-pop" v-if="regTipPop">
      <div style="width:100%;height:100%;" @click="regTipPop=false"></div>
      <div class="pay-bg" style="text-align: center">
        <p>您还不是会员，请先完成注册</p>
        <div class="reg-btn" @click="toRegister()">去注册</div>
      </div>
    </div>
    <div class="pay-pop" v-if="purchaseApplyPop">
      <div style="width:100%;height:100%;" @click="purchaseApplyPop=false"></div>
      <div class="pay-bg" style="text-align: center">
        <p>确定提交补货申请?</p>
        <div class="reg-btn" @click="areaAgentOrder()">确定</div>
        <div class="reg-btn cancel-btn"  @click="purchaseApplyPop=false">取消</div>
      </div>
    </div>
    <TextPop v-if="orderSuccess" :textPop="popOrderSuccess"></TextPop>

    <!--调用高德地图-->
    <iframe v-if="gaodeMap" @load="loadIframe" id="test"
            :src="'https://m.amap.com/picker/?keywords='+addressData.addressDetails+'&center='+destLatLng+'&key='+mapKey"
            frameborder="0"></iframe>
  </div>
</template>

<script>
  import global from '../public/global.vue'
  import wx from 'weixin-js-sdk'

  export default {
    name: 'buyNow',
    data() {
      return {
        areaName: "",
        areaId: "",
        markList: ["重要客户", "工作日18点以后配送", "非工作日早上9点以后配送"],//快捷标签
        //goodsNum: 1,//购买数量
        role: '',//角色
        personNum: [2, 3, 4, 5, 6, 7, 8, 9, 10],//选择人数
        showPop: false,//弹窗显示
        tabs: ["历史", "关注", "全部"],//服务商选择
        isOn: 0,//选择tab后 内容切换
        tabContent: [],
        goodsInfo: [],//商品详情
        totalMoney: 0,//合计
        totalMoneyDiscount: 0,//折后价
        userMessage: [],//用户留言
        isPop: false,//弹窗显示
        popText: '下单成功',
        recipients: '',//收件人
        mobile: '',//收件人电话
        addressData: {},//收货地址
        payPopShow: false,//显示提交支付方式弹窗
        payMode: 0,//默认支付方式微信支付
        gaodeMap: false,//显示高德地图
        paySign: '',
        nonceStr: '',
        prepay_id: '',
        appId: '',
        timeStamp: '',
        sourceUrl: global.sourceUrl,
        userLevel: {},//用户信息
        regTipPop: false,//注册提示弹窗
        discount: 1,//会员折扣
        originalPrice: 0,
        mapKey: global.mapKey,
        roleLevel: 1,//服务商等级
        isReplenishment: false,//是否从进货入口进入
        realName: "",
        popOrderSuccess: "下单成功",
        orderSuccess: false,
        boxSum: '',//包厢
        boxTime: '',
        boxDate: '',
        boxNum: '',
        tip: 0,
        isUpgradePatch: false,//是否为升级包
        isActivity: false,//是否为活动商品
        realImg: '',
        tabParent: {},//直推人
        destLatLng: "",//经纬度
        addressComponent: "",//省市区
        shoppingCartListId:[],
        imgHeight:'',
        myLevel:1,
        purchaseApplyPop:false,//补货申请弹窗
      }
    },

    methods: {

      //
      addrChange() {
        let self = this;
//        console.log(this.addressData.addressDetails);
        setTimeout(() => {
          AMap.plugin('AMap.Geocoder', function () {
            var geocoder = new AMap.Geocoder({
              // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
              city: self.addressComponent,
            })
            geocoder.getLocation(self.addressData.addressDetails, function (status, result) {
              if (status === 'complete' && result.info === 'OK') {
                // result中对应详细地理坐标信息
                self.destLatLng = result.geocodes[0].location.lng + ',' + result.geocodes[0].location.lat;
              }
            })
          })
        }, 100)

      },
      //iframe调用高德地图
      loadIframe() {
        let _this = this;
        let selectAddr = "";
        let iframe = document.getElementById('test').contentWindow;


        iframe.postMessage('hello', 'https://m.amap.com/picker/');
        window.addEventListener("message", function (e) {
          _this.gaodeMap = false;
          selectAddr = e.data.address + e.data.name;
          _this.addressData.addressDetails = selectAddr?selectAddr:'';
        }, true);

      },
      // 打开高德地图选址
      goAddress() {
        this.gaodeMap = true;
//        this.$router.push({path: '/myAddress?type=back'});
      },
      upperCase() {
        let num = parseFloat(this.tip);

        this.totalMoneyAll = parseFloat(this.totalMoney) + num;
        this.originalPriceAll = parseFloat(this.originalPrice) + num;
      },
      //数量加
      addNum(idx) {
        this.goodsInfo[idx].goodsNum++;
        let totalMone = 0;
        let originalPrice = 0;
        for (let i = 0; i < this.goodsInfo.length; i++) {
          totalMone += this.goodsInfo[i].shopPrice * this.goodsInfo[i].goodsNum * this.goodsInfo[i].goodsUnit;
          originalPrice += this.goodsInfo[i].marketPrice * this.goodsInfo[i].goodsNum * this.goodsInfo[i].goodsUnit;
        }
        this.totalMoney = (totalMone * this.discount).toFixed(2);
        this.originalPrice = originalPrice.toFixed(2)
      },
      //数量减
      minusNum(idx) {

        if (this.goodsInfo[idx].goodsNum > 1) {
          this.goodsInfo[idx].goodsNum--;
          let totalMone = 0;
          let originalPrice = 0;
          for (let i = 0; i < this.goodsInfo.length; i++) {
            totalMone += this.goodsInfo[i].shopPrice * this.goodsInfo[i].goodsNum * this.goodsInfo[i].goodsUnit;
            originalPrice += this.goodsInfo[i].marketPrice * this.goodsInfo[i].goodsNum * this.goodsInfo[i].goodsUnit;
          }
          this.totalMoney = (totalMone * this.discount).toFixed(2);
          this.originalPrice = originalPrice.toFixed(2)
//          this.totalMoney = this.goodsInfo.shopPrice * this.buyNum;
//          this.totalMoneyDiscount = ((this.goodsInfo.shopPrice*0.85) * this.buyNum).toFixed(2);
        }
      },
      //监听buynum变化
      changedValue(value) {
        alert(1)
//        this.goodsNum = document.getElementById('buynum').value;
//        this.totalMoney = this.goodsInfo.shopPrice * this.buyNum;
//        this.totalMoneyDiscount = (this.goodsInfo.shopPrice * this.buyNum).toFixed(2);
      },
      //快捷标签选择
      selectMark(idx) {
        if (this.userMessage.indexOf(this.markList[idx]) == -1) {
          this.userMessage.push(this.markList[idx]);
        }

      },
      //服务商 打开弹窗
      openPop() {
        let level = global.getCookie("level")
        if(level==6&&this.isReplenishment){
          return ;
        }
        this.showPop = true;
      },
      //弹窗tab切换
      switchTab(idx) {
        this.isOn = idx;
        let self = this;
        let url = global.apiUrl;
        let uid = global.getCookie("uid");
        if (!this.isReplenishment) {
          if (idx == 0) {
            url += '/sommelier/sommelierHistory?uid=' + uid;
          } else if (idx == 1) {
            url += '/sommelier/sommelierFollow?uid=' + uid;
          } else {
            url += '/sommelier/getAgentListAll';
          }
          self.$http.get(url).then(res => {
            self.tabContent = res.data.data;
            if (idx == 2) {
              self.$http.get(global.apiUrl + "/sommelier/getParent").then(res => {
                res.data.data.zfb = "1"
                self.tabContent.unshift(res.data.data)
              })
            } else {
              self.tabParent = null;
            }
          })
        } else {
          if (idx == 0) {
            url += '/sommelier/replenishAgentHistory';
          } else if (idx == 1) {
            url += '/sommelier/sommelierFollowAgent';
          } else {
            url += '/sommelier/selectAboveAgent';
          }

          self.$http.get(url).then(res => {
            self.tabContent = res.data.data;
            if (idx == 2) {
              self.$http.get(global.apiUrl + "/sommelier/getParent").then(res => {
                res.data.data.zfb = "1"
                self.tabContent.unshift(res.data.data)
                console.log(self.tabContent)
              })
            } else {
              self.tabParent = null;
            }
          })
        }


      },
      //服务商选择
      selectRole(uid, name, level, imageUrl) {
        //this.areaName=name;
        this.areaId = uid;
        this.showPop = false;
        this.roleLevel = level;
        this.realName = name;
        this.realImg = imageUrl;
        let pingjians = new Object();
        pingjians.name = name;
        pingjians.level = level;
        pingjians.id = uid;
        pingjians.realImg = imageUrl;
        window.localStorage.setItem("pingjians", JSON.stringify(pingjians));
      },
      //提交订单
      buyNowBtn() {
        if(this.goodsInfo[0].upgradePatch!=0){
          if(!window.confirm('付款后不能取消升级包订单，请您确认是否付款？')){
            return;
          }
        }
        if (this.goodsInfo[0].isActivity == 1) {
          this.$http.get(global.apiUrl + '/order/buyingCheck')
            .then(res => {
//              console.log(res);
              if (res.data.code == 0) {
                if (this.userLevel == 1) {
                  this.regTipPop = true;
                  return;
                }
                this.payPopShow = true;//打开支付方式弹窗
              } else {
                alert("对不起，您已经参加过0元购活动啦!")
              }
            }).catch(function (err) {
            console.error(err);
          })
        } else {
          if (this.userLevel == 1) {
            this.regTipPop = true;
            return;
          }
          this.payPopShow = true;//打开支付方式弹窗
        }
      },
      //弹窗支付
      payBtn() {

        let isReplenishment = this.isReplenishment;
        let level = this.$route.params.level;//角色
        let agentId = this.areaId;
        let goodsNumber = 1;
        let uid = global.getCookie("uid");
        let message = this.userMessage;
        let address = new Object();
//        address.address = this.addressData.address  + this.addressData.addressDetails;
        address.address =  this.addressData.addressDetails;
        address.receiver = this.recipients;
        address.mobile = this.mobile;
        if (address.mobile == "" || address.receiver == "" || address.address == '') {
          alert("请输入收货信息");
          this.payPopShow = false;
          return;
        }
        if (agentId == undefined || agentId == "undefined") {

          if (this.goodsInfo[0].upgradePatch > 0) {

          } else {
            alert("请选择服务商");
            return;
          }
        }
//        if (this.goodsInfo[0].upgradePatch > 0) {
//          agentId = 0
//        }
        //余额支付方式检查余额
        if (this.payMode == 1) {
          this.checkAccount();
        }
        this.payPopShow = false;//关闭支付方式弹窗
        let add = new Array();
        let op = new Array();
        var goodList = this.goodsInfo;
        for (var i = 0; i < goodList.length; i++) {

          let orderProducts = new Object();
          orderProducts.goodsId = goodList[i].id;
          orderProducts.goodsName = goodList[i].goodsName;
          orderProducts.price = goodList[i].shopPrice;
          orderProducts.orderNumber = goodList[i].goodsNum;
          orderProducts.fee = this.totalMoney;
          op.push(orderProducts)
        }


        let params = new URLSearchParams();
        params.append('uid', uid);
        params.append('orderProducts', JSON.stringify(op));
        params.append('goodsNumber', goodsNumber);
        if (this.totalMoney == undefined) {
          this.totalMoney = 1;
        }
        params.append('totalMoney', this.totalMoney);


        params.append('agentId', agentId);

        if (this.roleLevel == 3) {
          params.append('boxSum', this.boxSum);
          params.append('boxTime', this.boxTime);
          params.append('boxDate', this.boxDate);
          params.append('boxNum', this.boxNum);
          params.append('tip', this.tip);
        }else{
          level=global.getCookie("level");
          if(level>this.roleLevel){
            alert("服务商等级过低暂无法购买");
            return;
          }
        }

        if (this.isReplenishment) {
          params.append('orderType', 3);
        } else {
          if (this.roleLevel > 3) {
            params.append('orderType', 1);
          } else {
            params.append('orderType', 2);
          }
        }
        params.append('address', JSON.stringify(address));
        params.append('message', message);
        if(this.shoppingCartListId){
          params.append("shoppingCartListId",this.shoppingCartListId);
        }
        this.$http({
          url: global.apiUrl + '/order/createOrder',
          method: 'post',
          data: params,
        }).then(res => {
//          console.log(res);
          let billNo = res.data.data.billNo;
          let params = new URLSearchParams();
          params.append('billNo', billNo);
          if (res.data.code == 0) {
//            this.isPop=true;
//            setTimeout(()=>{
//              this.isPop=false;
//              this.$router.push({path:'/myOrder/?sid=99'});
//            },2000)
            if (this.payMode == 1) {//余额支付
              this.$http({
                method: "post",
                url: global.apiUrl + '/account/payUseWallet',
                data: params,
              }).then(res => {
                if (res.data.code == 0) {
                  this.orderSuccess = true
                  setTimeout(() => {
                    this.orderSuccess = false;
                    if (!this.isUpgradePatch) {
                      if(!isReplenishment){
                        if (window.confirm('要生成邀请函么？')) {

                          let box = new Object();
                          box.time = this.boxDate + "T" + this.boxTime;
                          box.addr = this.addressData.addressDetails;
                          box.num = this.boxNum;
                          box.phone = this.mobile;
                          window.localStorage.setItem("box", JSON.stringify(box));
                          this.$router.push({path: '/newly/?type=buy'});

                        }else{
                          this.$router.push({path: '/shop'});
                        }
                      }
                      else {
                        this.$router.push({path: '/shop'});
                      }
                    }else{
                      this.$router.push({path: '/shop'});
                    }


                  }, 1500)
                }
                else {
//                  alert("支付失败");
                  setTimeout(() => {
                    this.$router.push({path: '/myOrder/?sid=99'});
                  }, 500)
                }
              }).catch(function (err) {
                console.error(err);
              })
            } else {//微信支付
              this.$http({
                method: "post",
                url: global.apiUrl + '/pay/payOrder',
                data: params,
              }).then(res => {
                if (res.data.code == 0) {
                  this.appId = res.data.data.appId;
                  this.nonceStr = res.data.data.nonceStr;
                  this.paySign = res.data.data.paySign;
                  this.prepay_id = res.data.data.package;
                  this.timeStamp = res.data.data.timeStamp;
                  this.onBridgeReady();
                }
              }).catch(function (err) {
                console.error(err);
              })
            }
          } else {
            alert(res.data.data.msg)
          }
        }).catch(function (err) {
          console.error(err);
        });
      },
      //微信支付接口调用
      onBridgeReady() {
        let self = this;
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
            "appId": self.appId, //公众号名称，由商户传入
            "timeStamp": self.timeStamp, //时间戳，自1970年以来的秒数
            "nonceStr": self.nonceStr, //随机串
            "package": self.prepay_id,
            "signType": "MD5", //微信签名方式：
            "paySign": self.paySign //微信签名
          },
          function (res) {
//            console.log("--支付拉起--")
//            console.log(JSON.stringify(res));
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              //$.toast(JSON.stringify(res));
              // var html = '<div class="weui-msg"><div class="weui-msg__icon-area"><i class="weui-icon-success weui-icon_msg"></i></div><div class="weui-msg__text-area"><h2 class="weui-msg__title">支付成功</h2></div></div>';
              //window.location = "/page/pay_success.html";
              self.isPop = false;
              self.$router.push({path: '/shop'});
              // $("#content-box").html(html);
              // $.toast("支付成功", "text");
              // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
              //alert("支付成功");
            } else {
              //$.toast(JSON.stringify(res));
//              $.toast("支付失败", "text");
              alert("支付失败");
              setTimeout(() => {
                this.$router.push({path: '/myOrder/?sid=99'});
              }, 500)
            }
          }
        );

      },
      //关闭弹窗
      closePop() {
        this.showPop = false;
      },
      toRegister() {
        this.$router.push({path: '/registerMember'});
      },
      checkAccount() {
        this.$http.get(global.apiUrl + "/account/checkAccount", {
          params: {money: this.totalMoney}
        }).then(res => {
//          console.log(res.data);
          if (res.data.code == 0) {
            if (res.data.data.enough == 0) {
              alert("钱包余额不足！请选择其他支付方式")
            } else {

            }
          }
        }).catch(function (err) {
          console.error("Error:" + err);
        })
      },
      //输入打赏金额
      inputAwarad(){
//        console.log(this.tip);
        if(this.tip !=''&& this.tip.substr(0,1) == '.'){
          this.tip="";
        }
        this.tip = this.tip.replace(/^0*(0\.|[1-9])/, '$1');//解决 粘贴不生效
        this.tip = this.tip.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
        this.tip = this.tip.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
        this.tip = this.tip.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        this.tip = this.tip.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
        if(this.tip.indexOf(".")< 0 && this.tip !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          if(this.tip.substr(0,1) == '0' && this.tip.length == 2){
            this.tip= this.tip.substr(1,this.tip.length);
          }
        }
      },
      areaAgentOrder(){
        this.purchaseApplyPop = false
        let level = this.$route.params.level;//角色
        let agentId = this.areaId;
        let goodsNumber = 1;
        let uid = global.getCookie("uid");
        let message = this.userMessage;
        let address = new Object();
        address.address =  this.addressData.addressDetails;
        address.receiver = this.recipients;
        address.mobile = this.mobile;
        if (address.mobile == "" || address.receiver == "" || address.address == '') {
          alert("请输入收货信息");
          this.payPopShow = false;
          return;
        }
        this.payPopShow = false;//关闭支付方式弹窗
        let add = new Array();
        let op = new Array();
        var goodList = this.goodsInfo;
        for (var i = 0; i < goodList.length; i++) {
          let orderProducts = new Object();
          orderProducts.goodsId = goodList[i].id;
          orderProducts.goodsName = goodList[i].goodsName;
          orderProducts.price = goodList[i].shopPrice;
          orderProducts.orderNumber = goodList[i].goodsNum;
          orderProducts.fee = this.totalMoney;
          op.push(orderProducts)
        }
        let params = new URLSearchParams();
        params.append('uid', uid);
        params.append('orderProducts', JSON.stringify(op));
        params.append('goodsNumber', goodsNumber);
        if (this.totalMoney == undefined) {
          this.totalMoney = 1;
        }
        params.append('totalMoney', this.totalMoney);
        params.append('agentId', 200);
        params.append('orderType', 4);
        params.append('address', JSON.stringify(address));
        params.append('message', message);
        if(this.shoppingCartListId){
          params.append("shoppingCartListId",this.shoppingCartListId);
        }
        this.$http({
          url: global.apiUrl + '/order/createOrder',
          method: 'post',
          data: params,
        }).then(res => {
          if(res.data.code==0){
            alert("下单成功！")
            this.$router.push({path: '/myOrder/?sid=99'});
          }else{
            alert(res.data.msg)
          }
        }).catch(function (err) {
          console.error(err);
        });
      },
      purchaseApply(){
        this.purchaseApplyPop = true
      }
    },
    computed: {
      tip: {
        get() {
          return this.oldNum;
        },
        set(newValue) {
          this.oldNum = newValue.replace(/[^\d]/g, '');
        }
      }
    },

    //页面创建完成
    created: function () {
      // this.areaId = this.$route.params.uid;
      let pid = this.$route.params.id;

      let type = this.$route.params.type;

      let self = this;
      this.myLevel = global.getCookie("level")
      this.shoppingCartListId = this.$route.params.shoppingCartListId

      self.mobile = window.localStorage.getItem("mobile");
      if (self.mobile == null || self.mobile == "undefined") {
        self.mobile = "";
      }
      self.recipients = window.localStorage.getItem("name");
      if (self.recipients == null || self.recipients == "undefined") {
        self.recipients = "";
      }
      self.role = this.$route.params.level;
      self.roleLevel = this.$route.params.level;


      let url = global.apiUrl;
      let isReplenishment = this.$route.params.isReplenishment;
      if (isReplenishment != 1) {
        let pingjians = window.localStorage.getItem("pingjians");
        if (pingjians != null || pingjians != undefined) {
          pingjians = JSON.parse(pingjians);
          self.roleLevel = pingjians.level;
          self.realName = pingjians.name;
          self.areaId = pingjians.id;
          self.realImg = pingjians.realImg;
        }else{
          self.$http.get(url + "/sommelier/getParent").then(res => {
            if(res.data.code==0){
              self.roleLevel = res.data.data.level;
              self.realName = res.data.data.name;
              self.areaId = res.data.data.id;
              self.realImg = res.data.data.imageUrl;

            }
          })
        }
      }else{
        self.$http.get(url + "/sommelier/getParent").then(res => {
          if(res.data.code==0){
            self.roleLevel = res.data.data.level;
            self.realName = res.data.data.name;
            self.areaId = res.data.data.id;
            self.realImg = res.data.data.imageUrl;
            //区域代理商补货默认选择公司
            let level = global.getCookie("level");
            if(level==6&&isReplenishment==1){
              self.realName = "英拉总部";
            }
          }

        })


        self.$http.get(url + "/sommelier/getParent").then(res => {
          if(res.data.code==0){
            self.roleLevel = res.data.data.level;
            self.realName = res.data.data.name;
            self.areaId = res.data.data.id;
            self.realImg = res.data.data.imageUrl;




            if(res.data.data.level<=global.getCookie("level")){
              self.$http.get(url + "/sommelier/selectAboveAgent").then(res => {
                self.roleLevel = res.data.data[0].level;
                self.realName = res.data.data[0].name;
                self.areaId = res.data.data[0].id;
                self.realImg = res.data.data[0].imageUrl;

              })
            }
          }else{
            self.$http.get(url + "/sommelier/selectAboveAgent").then(res => {
              self.roleLevel = res.data.data[0].level;
              self.realName = res.data.data[0].name;
              self.areaId = res.data.data[0].id;
              self.realImg = res.data.data[0].imageUrl;
            })
          }
          //区域代理商补货默认选择公司
          let level = global.getCookie("level");
          if(level==6&&isReplenishment==1){
            self.realName = "英拉总部";
          }
        })
      }
      this.isReplenishment = this.$route.params.isReplenishment;
      if (isReplenishment) {
        this.$http.get(url + '/user/getDiscountByLevel').then(res => {
          if (res.data.code == 0) {
            this.discount = res.data.data;
//            console.log(this.discount)
          } else {
            this.discount = 1
          }
        })
        this.$http.get(url + '/sommelier/purchaseAgent').then(res => {
          if (res.data.code == 0) {
            this.tabContent = res.data.data;
          }
        })
      } else {
        this.$http.get(url + '/user/getDiscount').then(res => {
          if (res.data.code == 0) {
            this.discount = res.data.data.paramValue;
//            console.log(this.discount)
          } else {
            this.discount = 1
          }
        })
      }


      //获取默认地址
      self.$http.get(url + '/userAddress/getDefauls').then(res => {
        if (res.data.data == null) {
          self.addressData.address = "";
          self.addressData.addressDetails = "";
          self.addressData.name = "";
          self.addressData.phone = "";
        } else {
          self.addressData.addressDetails = res.data.data.address + res.data.data.addressDetails;
        }

      })

      if (type == undefined) {

        let buyNow = window.localStorage.getItem("buyNow");


        buyNow = JSON.parse(buyNow);
        type = buyNow.type;
        this.areaId = buyNow.uid;
        pid = buyNow.id;
//        let addressId = window.localStorage.getItem("address");
//        self.$http.get(url + "/userAddress/getAddress?id=" + addressId).then((res) => {
//          self.addressData = res.data.data;
//        })
      } else {
        window.localStorage.setItem("buyNow", JSON.stringify(this.$route.params));
      }


      if (type == "car") {
        let ps = window.localStorage.getItem("prods");
        let prods = JSON.parse(ps);
//        console.log(prods);
        var num = 0;
        var original = 0;
        for (let i = 0; i < prods.length; i++) {
          let prod = prods[i];
          self.$http.get(url + '/goods/getGoodsDetail', {
            params: {
              id: prod.goodsId,
            }
          }).then(res => {

            if (res.data.code == 0) {
              var obj = res.data.data;
              obj.goodsNum = prods[i].orderNumber;
              self.goodsInfo.push(obj);
              num += prods[i].orderNumber * obj.shopPrice * obj.goodsUnit;
              original += prods[i].orderNumber * obj.marketPrice * obj.goodsUnit;
              //self.originalPrice = prods[i].orderNumber * obj.marketPrice * obj.goodsUnit
              self.originalPrice = original.toFixed(2)
              self.totalMoney = (num * this.discount).toFixed(2);
              if (obj.isActivity == 1) {
                self.totalMoney = obj.shopPrice
                self.isActivity = true
              }
            }
          }).catch(function (err) {
            console.error(err);
          });
        }
        if (this.goodsInfo[0].upgradePatch > 0) {
          this.isUpgradePatch = true
        }


      } else {

        self.$http.get(url + '/goods/getGoodsDetail', {
          params: {
            id: pid,
          }
        }).then(res => {
//        console.log(res);
          if (res.data.code == 0) {
            var obj = res.data.data;
            obj.goodsNum = 1;
            self.goodsInfo.push(obj);
            self.totalMoney = (obj.shopPrice * obj.goodsUnit * this.discount).toFixed(2);
            if (obj.isActivity == 1) {
              self.totalMoney = obj.shopPrice
              self.isActivity = true
            }
            self.originalPrice = obj.marketPrice * obj.goodsUnit
            if (self.goodsInfo[0].upgradePatch > 0) {
              self.isUpgradePatch = true
            }
          }
        }).catch(function (err) {
          console.error(err);
        });
      }
      let uid = global.getCookie("uid");
//      console.log(isReplenishment)
      if (!isReplenishment) {
        self.$http.get(url + '/sommelier/sommelierHistory?uid=' + uid).then(res => {
          self.tabContent = res.data.data;
        })
      } else {
        self.$http.get(url + '/sommelier/replenishAgentHistory').then(res => {
          self.tabContent = res.data.data;
        })
      }

      this.$http.get(url + '/user/getUserInfo').then(res => {
        if (res.data.code == 0) {
          this.userLevel = res.data.data.userInfo.level;
        } else {
          this.userLevel = 0
        }

      })



    },
    mounted: function () {
      let self=this;
      document.title = "立即购买";
      this.$nextTick(function () {
        if (!self.addressData.addressDetails || self.addressData.addressDetails == undefined) {
          self.addressData.addressDetails = '';
        }
        let addressComponent = self.$store.getters.getAddressComponent;
        self.addressComponent = addressComponent;
        self.addressData.addressDetails = addressComponent;

      })
      setTimeout(()=>{
        self.imgHeight=self.$refs.imgWidth[0].clientWidth+'px';
      },500)
    },

  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
  @pd10: 10px;
  .buy-now-box {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    background: #f3f3f3;
    padding-bottom: 50px;
    /*公共类*/
    .pd10 {
      width: 100%;
      padding: @pd10;
      background: #fff;
      margin-bottom: 10px;
    }
    .session {
      width: 100%;
      line-height: 1.5rem;
      font-size: 1rem;
      .row-left {
        display: inline-block;
        width: 21%;
        /*white-space: nowrap;*/
        text-align: justify;
        text-align-last: justify;
        text-justify: inter-ideograph;
        vertical-align: top;
      }
      textarea, input {
        width: 65%;
        font-size: 1rem;
        border: none;
        outline: none;
        resize: none;
      }
      textarea {
        overflow-y: visible;
        font-size: 1rem;
        line-height: 1.1rem;
        padding-top: 4px;
      }
      .selectAddress {
        display: inline-block;
        width: 64%;
        font-size: 1rem;
      }
      img {
        width: 15px;
        vertical-align: top;
      }
    }
    i.arrow-right {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-right: 1px solid #aaa;
      border-bottom: 1px solid #aaa;
      transform: rotateZ(-45deg);
    }
    /*商品信息*/
    .row {
      display: flex;
      .col-left {
        width: 36%;
        margin-right:4%;
        img {
          width: 100%;
          height:100%;
        }
      }
      .col-right {
        width: 60%;
        font-size: 0.9rem;
        color: #666;
        .title {
          height: 2.5rem;
        }
        .price {
          color: #ff0000;
          margin-top: 5px;
        }
        .num-box {
          width: 100%;
          display: flex;
          justify-content: space-between;
          .nb-left {
            width: 100%;
          }
          .nb-right {
            width: 80%;
            text-align: right;
            img {
              width: 20px;
              vertical-align: middle;
            }
            input {
              width: 28px;
              vertical-align: middle;
              border: none;
              outline: none;
              text-align: center;
              /*padding: 0 4px;*/
            }
          }
        }
      }
    }
    /*服务商*/
    .row2 {
      display: flex;
      justify-content: space-between;
      .r-left {
        font-size: 1rem;
        color: #333;
      }
      .r-right {
        text-align: right;
        img {
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }
      }
    }
    /*服务商弹窗*/
    .pop-box {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, .5);
      .pop-bg {
        position: absolute;
        top: 20%;
        left: 0;
        right: 0;
        margin: auto;
        width: 80%;
        overflow: hidden;
        background: #fff;
        border-radius: 6px;
        .tab-box {
          width: 100%;
          height: 2rem;
          line-height: 2rem;
          padding: 0 10px;
          display: flex;
          font-size: 1rem;
          li {
            flex: 1;
            text-align: center;
            span {
              display: inline-block;
              height: 100%;
              padding: 0 10%;
              box-sizing: border-box;
            }
            .on {
              border-bottom: 2px solid #FB5353;
            }
          }
        }
        .tab-content {
          width: 100%;
          height: 200px;
          padding: 10px;
          overflow: auto;
          border-top: 2px solid #eee;
          li {
            width: 100%;
            padding: 4% 0;
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #eee;
            font-size: 0.9rem;
            .li-left {
              width: 50%;
              display: flex;
              .img-box {
                width: 40%;
                img {
                  width: 40px;
                  height: 40px;
                  border-radius: 50%;
                  vertical-align: middle;
                }
              }
              .name-box {
                width: 60%;
                vertical-align: middle;
                .p-name {
                  font-size: 0.95rem;
                }
                .p-agent {
                  display: inline-block;
                  font-size: 0.8rem;
                  color: #fff;
                  padding: 0 10%;
                  text-align: center;
                  border-radius: 30px;
                }
                .blue {
                  background: #72A4FF;
                }
                .yellow {
                  background: #FCBD06;
                }
                .red {
                  background: #FB3C3D;
                }
              }
            }
            .li-right {
              width: 50%;
              text-align: right;
              font-size: 0.9rem;
              line-height: 1.2rem;
              .p-gender {
                color: #aaa;
              }
              .p-distance {
                color: #ff0000;
              }
            }
          }
        }
        .tab-content::-webkit-scrollbar {
          display: none;
        }
      }
    }
    /*地址 收件人 电话*/
    .row-p {
      width: 100%;
      padding: 1.5% 0;
      font-size: 1rem;
      span {
        display: inline-block;
        width: 22%;
        font-size: 1rem;
        color: #333;
      }
      input {
        width: 65%;
        height: 1rem;
        line-height: 1rem;
        padding: 0 1%;
        border: none;
        outline: none;
        font-size: 0.9rem;
      }
      img {
        width: 14px;
        float: right;
      }
      .arrow-right {
        float: right;
        margin-top: 4px;
      }
    }
    .row-sliers {
      padding: 0;
      display: flex;
      justify-content: space-between;
      white-space: nowrap;
      span {
        flex: 1;
      }
      span:last-child {
        text-align: right;
        margin-right: 20px;
      }
    }
    .row-addr {
      padding: 0;
      span {
        width: 95%;
      }
      .arrow-right {
        margin-top: 8px;
      }
    }
    .input-box {
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      font-size: 1rem;

      li {
        width: 50%;
        margin: 5px auto;
        span {
          display: inline-block;
          width: 22%;
        }
        input {
          -webkit-appearance: none;
          width: 60%;
          height: 30px;
          padding: 0 2px;
          -webkit-box-sizing: border-box;
          -moz-box-sizing: border-box;
          box-sizing: border-box;
          font-size: 1rem;
          color: #aaa;
          outline: none;
          border: none;
          background: transparent;
          border-bottom: 1px solid #eee;
        }
        .select-box {
          display: inline-block;
          width: 60%;
          margin-left: -5px;
          select {
            width: 100%;
            -webkit-appearance: none;
            outline: none;
            border: none;
            background: transparent;
            border-bottom: 1px solid #eee;
            background: url('../../assets/images/pull_down.png') no-repeat right top;
            background-size: contain;
          }
        }
        img {
          width: 15px;
          float: right;
        }
      }
      li:nth-child(n-3) {
        width: 100%;
      }
    }
    /*留言*/
    .area-box {
      width: 100%;
      label {
        display: inline-block;
        width: 18%;
        font-size: 1rem;
        color: #333;
        vertical-align: top;
      }
      textarea {
        width: 80%;
        min-height: 4rem;
        padding: 2px;
        border: 1px solid #ddd;
        border-radius: 6px;
        resize: none;
        outline: none;
        font-size: 1rem;
        box-sizing: border-box;
      }
    }
    /*快捷标签*/
    .mark-box {
      font-size: 1rem;
      p {
        color: #aaa;
        margin: 10px auto;
      }
      .mark-list {
        display: flex;
        flex-wrap: wrap;
        li {
          color: #666;
          padding: 2px 5%;
          margin-right: 10px;
          margin-bottom: 10px;
          background: #F3F3F3;
          border-radius: 30px;
        }
      }
    }
    /*底部提交*/
    .submit-box {
      position: fixed;
      bottom: 0;
      width: 100%;
      height: 50px;
      line-height: 50px;
      background: #fff;
      border-top: 1px solid #ddd;
      display: flex;
      justify-content: space-between;
      font-size: 1rem;
      .col-left {
        padding: 0 5px 0 10px;;
        color: #333;
        span {
          color: #ff0000;
        }
        .original-price {
          font-size: 13px;
          text-decoration: line-through;
          color: gray
        }
        .discount {
          font-size: 0.8rem;
          text-decoration: line-through;
          color: #aaa;
        }
      }
      .col-right {
        padding: 0 10px 0 5px;
        span {
          padding: 5px 10px;
          background: #D85353;
          font-size: 0.9rem;
          color: #fff;
          border-radius: 30px;
          font-weight: 200;
        }
      }
    }
    /*提交弹窗*/
    .pay-pop {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, .5);
      .pay-bg {
        position: absolute;
        top: 30%;
        left: 0;
        right: 0;
        width: 90%;
        margin: auto;
        background: #fff;
        padding: 5% 10%;
        border-radius: 6px;
        .price {
          height: 3rem;
          line-height: 3rem;
          font-size: 1.5rem;
          text-align: center;
          margin-bottom: 10px;
        }
        label {
          display: block;
          height: 2rem;
          line-height: 2rem;
          text-align: center;
          border-bottom: 1px solid #eee;
          font-size: 1rem;
          font-weight: inherit;
          input {
            -webkit-appearance: radio;
            width: 20px;
            height: 20px;
            vertical-align: middle;
            margin: 0;
          }
          span {
            margin-left: 10%;
            vertical-align: middle;
          }
        }
        .pay-btn {
          width: 100%;
          height: 2rem;
          line-height: 2rem;
          font-size: 1rem;
          color: #fff;
          background: #d44242;
          border-radius: 6px;
          text-align: center;
          margin-top: 20px;
        }
      }
    }
    .reg-btn {
      width: 60%;
      height: 2rem;
      line-height: 2rem;
      font-size: 1rem;
      color: #fff;
      background: #d44242;
      border-radius: 6px;
      text-align: center;
      margin-top: 20px;
      margin-left: 55px;
    }

    /*高德地图*/
    iframe {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: #fff;
      z-index: 100;
    }

  }
</style>
